package com.feige.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;


/**
 * @author feige
 */
@Slf4j
@Component
public class NettyServer {

    @Resource
    private NettyServerInitializer nettyServerInitializer;

    @Value("${netty.server.port}")
    private int initPort;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workGroup;
    private ChannelFuture channelFuture;


    public void start() throws InterruptedException {
        bossGroup = new NioEventLoopGroup();
        workGroup = new NioEventLoopGroup();
        //ServerBootstrap负责初始化netty服务器，并且开始监听端口的socket请求
        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup,workGroup)
                .localAddress(this.initPort)
                //配置双向通道
                .channel(NioServerSocketChannel.class)
                //为监听客户端read/write事件的Channel添加用户自定义的ChannelHandler
                .childHandler(nettyServerInitializer);
        channelFuture = server.bind().sync();
        log.info("netty websocket server in\t"+this.initPort+"\tport start finish....");
    }

    @PreDestroy
    public void destroy(){
        if (this.bossGroup != null){
            this.bossGroup.shutdownGracefully();
        }
        if (this.workGroup != null){
            this.workGroup.shutdownGracefully();
        }
        if (this.channelFuture != null){
            this.channelFuture.channel().close();
        }
    }
}
